package com.ruoyi.project.app.service;

import ai.advance.cmp.api.client.bean.ResponseBean;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.intercepter.JwtHelperInterface;
import com.ruoyi.project.app.util.*;
import com.ruoyi.project.beautyflower.FaceScoreUtil;
import com.ruoyi.project.beautyflower.member.domain.Member;
import com.ruoyi.project.beautyflower.member.service.IMemberService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import com.ruoyi.project.beautyflower.order.domain.Order;
import com.ruoyi.project.beautyflower.order.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登录层
 */
@Service
public class AppLoginService implements JwtHelperInterface {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private OrderMapper orderMapper;//订单mapper

    //ios过审测试账号
    private final static String IOS_TEST_MOBILE = "15683410918";

    /**
     * 发送验证码
     *
     * @param phone
     * @param request
     * @return
     */
    public Map<String, String> sendCode(String phone, HttpServletRequest request, String type) {
        if (StringUtils.isNotBlank(phone)) {
            Map<String, String> map = Maps.newHashMap();
            if (PhoneUtils.getInstance().isMatcherPhone(phone)) {
                //生成4位随机数
                String code = String.valueOf((int) (Math.random() * 9000 + 1000));
                if(IOS_TEST_MOBILE.equals(phone)){
                    code = "0000";
                }
                try {
                    JSONObject jsonOs = KxtSmsUtil.sendSms(phone,code,type);
                    if(jsonOs.get("res_code").equals("0")){
                        map.put("code", code);
                        request.getSession().getServletContext().setAttribute(phone, new CodeEntity(type + "", code, new Date()));
                        return map;
                    }else{
                        throw new XException("短信发送失败，错误码："+jsonOs.get("res_code"));
                    }
                } catch (Exception e) {
                    throw new XException("服务端错误");
                }

            } else {
                throw new XException("请输入正确的手机号");
            }
        } else {
            throw new XException("手机号不能为空");
        }
    }


    /**
     * 登录
     *
     * @param phone
     * @param uuid
     * @return
     */
    @Transactional(readOnly = false)
    public Member login(String phone, String uuid, String code, HttpServletRequest request) {
        if (StringUtils.isNotBlank(phone)) {
            if (PhoneUtils.getInstance().isMatcherPhone(phone)) {
                if (StringUtils.isNotBlank(code)) {
                    //验证验证码是否有效
                    Object attribute = request.getSession().getServletContext().getAttribute(phone);
                    if (attribute instanceof CodeEntity) {
                        CodeEntity codeEntity = (CodeEntity) attribute;
                        //验证验证码是否存在
                        if (StringUtils.equals(codeEntity.getType(), "1")) {
                            //验证验证码是否一致
                            if (StringUtils.equals(codeEntity.getCode(), code)) {
                                //验证时间是否有效3分钟有效
                                if ((System.currentTimeMillis() - codeEntity.getDate().getTime()) > 180000) {
                                    throw new XException("验证码失效，请重新发送");
                                } else {
//                                    if(StringUtils.isBlank(uuid)){
//                                        throw new XException("手机设备号不能为空");
//                                    }
                                    Member member = memberService.selectMemberByPhone(phone);
                                    ResponseBean responseBean= FaceScoreUtil.queryUserInJuMeiByMobile(phone);
                                    //返回给用户数据
//                                    Map<String,Object> map=new HashMap<>();
                                    if (member != null) {
//                                        if (member.getUuid()!=null && !StringUtils.equals(member.getUuid(), uuid)) {
//                                            throw new XException("该手机设备不能登录");
//                                        }
//                    Member member1=memberService.findUniqueByProperty("uuid",uuid);
//                    if(user.getUuid() == null && user1!=null){
//                        throw new XException("该手机设备不能再登录另一个设备");
//                    }
                                        //创建新的token值
                                        String token = TokenUtil.get().createToken();
                                        member.setLatelyLoginDate(DateUtils.getTime());//最近一次登录时间
                                        member.setLoginCount(member.getLoginCount() + 1);//登录次数
                                        member.setToken(token);//用户密钥
                                        member.setUuid(uuid);//用户手机设备号
                                        //更新数据库
                                        if (StringUtils.isBlank(member.getNickName())) {
                                            member.setNickName("天美花00" + member.getId());
                                        }
                                        Order order=new Order();
                                        order.setMemberId(member.getId());
                                        List<Order> orderList= orderMapper.selectOrderList(order);
                                        if(orderList!=null&&orderList.size()>0){
                                            member.setWhetherLoanUser(2);
                                        }else{
                                            member.setWhetherLoanUser(1);
                                        }

                                        if(responseBean.getData()!=null){
                                            Map<String,Object> map=(Map<String,Object>)responseBean.getData();
                                            member.setGatherBeauty(map.get("userId")+"");
                                        }
                                        memberService.updateMember(member);
                                    } else {
                                        member = new Member();
                                        String token = TokenUtil.get().createToken();
                                        member.setFirstLoginDate(DateUtils.getTime());//首次登录时间
                                        member.setLoginCount(1);//用户登录次数
                                        member.setLatelyLoginDate(DateUtils.getTime());//最近一次登录时间
                                        member.setMobile(phone);//用户手机号
                                        member.setUuid(uuid);//手机设备号
                                        member.setToken(token);//用户密钥
                                        memberService.insertMember(member);
                                        member = memberService.selectMemberByPhone(phone);
                                        member.setNickName("天美花00" + member.getId());
                                        if(responseBean.getData()!=null){
                                            Map<String,Object> map=(Map<String,Object>)responseBean.getData();
                                            member.setGatherBeauty(map.get("userId")+"");
                                        }
                                        memberService.updateMember(member);

                                    }

                                    // Create Twt token
                                    member.setJwtToken(createJwt(member.getId(), member.getName()));
                                    // save jwt token
                                    Cache cache = cacheManager.getCache("system");
                                    cache.put("app_token_" + member.getId(), member.getJwtToken());
                                    return member;
                                }
                            } else {
                                throw new XException("验证码错误");
                            }
                        } else {
                            throw new XException("验证码错误");
                        }
                    } else {
                        throw new XException("验证码错误");
                    }
                } else {
                    throw new XException("验证码不能为空");
                }
            } else {
                throw new XException("请输入正确的手机号");
            }
        } else {
            throw new XException("请输入手机号");
        }
    }

    /**
     * 验证,验证码是否正确
     *
     * @param code
     * @param request
     * @param phone
     * @param type
     * @return
     */
    public Boolean verify(String code, HttpServletRequest request, String phone, String type) {
        //验证手机验证码是否有效
        if (StringUtils.isNotBlank(code)) {
            //验证验证码是否有效
            Object attribute = request.getSession().getServletContext().getAttribute(phone);
            if (attribute instanceof CodeEntity) {
                CodeEntity codeEntity = (CodeEntity) attribute;
                //验证验证码是否存在
                if (StringUtils.equals(codeEntity.getType(), type)) {
                    //验证验证码是否一致
                    if (StringUtils.equals(codeEntity.getCode(), code)) {
                        //验证时间是否有效3分钟有效
                        if ((System.currentTimeMillis() - codeEntity.getDate().getTime()) > 180000) {
                            throw new XException("验证码失效，请重新发送");
                        } else {
                            return true;
                        }
                    } else {
                        throw new XException("验证码错误");
                    }
                } else {
                    throw new XException("验证码错误");
                }
            } else {
                throw new XException("验证码错误");
            }
        } else {
            throw new XException("验证码不能为空");
        }
    }
}
